# -*- coding: utf-8 -*-
import unittest
import xlrd
import yaml
from bin.HTMLTestRunner import HTMLTestRunner
from config.config import testcase_path, report_file, description, reporttitle, tester, object_lib
from config.config import browser, driver_file
from config import logs
from selenium import webdriver


class InitTest(unittest.TestCase):
    def setUp(self):
        self.imgs = []
        self.logs = logs
        initlogs = self.logs.log_message('测试用例初始化')
        if browser.lower() == 'chrome':
            self.driver = webdriver.Chrome(driver_file)
        elif browser.lower() == 'firefox':
            self.driver = webdriver.Firefox(driver_file)
        else:
            raise NameError("- [InitTest]对象初始化：chrome，firefox；请检查config.py的browser是否正确")
        initlogs.logger.info('开始执行测试用例')

    def tearDown(self):
        downlogs = self.logs.log_message('测试用例执行完成')
        self.driver.quit()
        downlogs.logger.info('关闭浏览器\n')


def runtest():
    test_suit = unittest.TestSuite()
    discover = unittest.defaultTestLoader.discover(testcase_path, pattern='test*.py', top_level_dir=None)
    for test in discover:
        for test_case in test:
            test_suit.addTest(test_case)
    # 初始化测试数据 未做
    report = open(report_file, 'wb')
    runner = HTMLTestRunner(stream=report, title=reporttitle, description=description, tester=tester)
    runner.run(test_suit)
    report.close()


def init_datas(datapath, sheetname, module):
    log = logs.log_message('初始化测试数据')
    try:
        # 通过sheetname获取sheet对象
        sheet = xlrd.open_workbook(datapath).sheet_by_name(sheetname)
        nrows = sheet.nrows  # 总行数
        listdata = []
        for i in range(1, nrows):
            tmp_dic = {}
            # 用例名称
            tmp_dic['module'] = sheet.cell(i, 0).value  # 获取每行第一列内容
            if tmp_dic['module'] == module:  #
                # 步骤名称
                tmp_dic['case_name'] = sheet.cell(i, 1).value  # 获取每行第二列内容
                if sheet.cell(i, 2).value != "{}":
                    tmp_dic.update(eval(sheet.cell(i, 2).value))
                if sheet.cell(i, 3).value != "{}":
                    tmp_dic.update(eval(sheet.cell(i, 3).value))
                listdata.append(tmp_dic)
        log.logger.info('测试数据：%s' % listdata)
        return listdata
    except Exception as e:
        log.logger.error('获取测试用例数据失败，原因：%s' % e)


def init_objects(module):
    file = open(object_lib, "r", encoding="utf-8")
    objects = yaml.load(file)
    file.close()
    return objects[module]
